<?php
defined('BASEPATH') or exit('No direct script access allowed');

// require APPPATH . '/libraries/PHP/ChuanglanSmsHelper/ChuanglanSmsApi.php';
class Shopuser extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('shopuser_model');
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
    }

    // 发送短信验证码
    /**
     * @SWG\Post(
     *     summary="发送短信验证码",
     *     path="/shopuser/send_msg",
     *     tags={"商户端"},
     *     operationId="send_msg",
     *     produces={"application/json"},
     *     @SWG\Response(
     *         response=200,
     *         description="成功",
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="参数不全",
     *     ),
     *     @SWG\Parameter(
     *         description="电话号码",
     *         in="formData",
     *         name="tel",
     *         required=true,
     *         type="integer",
     *     )
     * )
     */
    // public function send_msg()
    // {
    //     $post = $this->input->post();
    //     if ($post['tel']) {
    //         // 手机号码校验
    //         if (!is_mobile($_POST['tel'])) {
    //             send_json(array('code' => 4001, 'data' => '', 'msg' => "请输入正确的手机号码"));
    //         }
    //         session_id($this->config->item("code_session_id"));
    //         session_start(600); //600秒以后过期。
    //         $code       = generate_code();
    //         $session_id = $this->config->item("code_session_id");
    //         $clapi      = new ChuanglanSmsApi();
    //         $result     = $clapi->sendSMS($_POST['tel'], "您好，您的短信验证码为：{$code},请在3分钟内完成验证！");
    //         if (!is_null(json_decode($result))) {
    //             $output = json_decode($result, true);
    //             if (isset($output['code']) && $output['code'] == '0') {
    //                 $data1['time']                    = date("Y-m-d H:i:s");
    //                 $data1['code']                    = $code;
    //                 $_SESSION[$_POST['tel'] . "code"] = json_encode($data1);
    //                 send_json(array('code' => 2000, 'data' => array('code' => '', 'session_id' => $session_id), 'msg' => "短信发送成功！"));
    //             } else {
    //                 send_json(array('code' => 4001, 'data' => '', 'msg' => $output['errorMsg']));
    //             }
    //         } else {
    //             send_json(array('code' => 4001, 'data' => '', 'msg' => $result));
    //         }
    //     } else {
    //         send_json(array('code' => 4001, 'msg' => '参数不全'));
    //     }
    // }
    public function send_msg()
    {
        //定义参数
        // http://api.zthysms.com/sendSms.do
        //关闭notice报错
        // error_reporting(0);
        $post = $this->input->post();
        if ($post['tel']) {
            // 手机号码校验
            if (!is_mobile($post['tel'])) {
                send_json(array('code' => 4001, 'data' => '', 'msg' => "请输入正确的手机号码"));
            }
            session_id($this->config->item("code_session_id"));
            session_start(); //600秒以后过期。
            $code    = generate_code();
            $content = "您好，您的短信验证码为：{$code},请在3分钟内完成验证！【佳品小栈】";
            //短信账号跟密码
            $url = 'http://api.zthysms.com/sendSms.do';
            $u   = 'AXKJhy';
            $p   = 'OjsGDE';
            require dirname(__FILE__) . "/../models/Smsapi_model.php";
            $sms  = new Smsapi_model($url, $u, $p);
            $data = array(
                'content'   => $content, //短信内容
                'mobile'    => $post['tel'], //手机号码
                'productid' => '', //产品id
                'xh'        => '', //小号
            );
            $sms->data = $data; //初始化数据包
            $res       = $sms->sendSMS('GET', true); //GET or POST
            $res       = explode(',', $res);
            if ($res[0] == 1) {
                $session_id                       = $this->config->item("code_session_id");
                $data1['time']                    = date("Y-m-d H:i:s");
                $data1['code']                    = $code;
                $_SESSION[$_POST['tel'] . "code"] = json_encode($data1);
                send_json(array('code' => 2000, 'data' => array('code' => '', 'session_id' => $session_id), 'msg' => "短信发送成功！"));
            } else {
                send_json(array('code' => 2000, 'data' => array('code' => '', 'session_id' => $session_id), 'msg' => "短信发送失败！"));
            }
        } else {
            send_json(array('code' => 4001, 'msg' => '参数不全'));
        }
    }

    /**  验证短信验证码
     * @param string $tel 手机号
     * @param string $code 输入验证码
     * @return bool
     */
    private function confirm_code_gerenal($tel = "", $code = "")
    {
        if (!is_mobile($_POST['tel'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "请输入正确的手机号码"));
        }
        session_id($this->config->item("code_session_id"));
        session_start();
        $rs = isset($_SESSION[$tel . "code"]) ? $_SESSION[$tel . "code"] : '';
        if ($rs) {
            $data   = json_decode($rs, true);
            $minute = floor((time() - strtotime($data['time'])) % 86400 / 60);
            if ($minute > 3) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "此验证码已超过3分钟,已失效或者验证码错误"));
            }

            if ($data['code'] == $code) {
                return true;
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "验证码错误"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "此手机没有发送验证码"));
        }
    }

    //商户登录
    /**
     * @SWG\Post(
     *     summary="商户登录",
     *     path="/shopuser/login",
     *     tags={"商户端"},
     *     operationId="login",
     *     produces={"application/json"},
     *     @SWG\Response(
     *         response=200,
     *         description="成功",
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="参数不全",
     *     ),
     *     @SWG\Parameter(
     *         description="电话号码",
     *         in="formData",
     *         name="tel",
     *         required=true,
     *         type="integer",
     *     ),
     *     @SWG\Parameter(
     *         description="验证码",
     *         in="formData",
     *         name="code",
     *         required=true,
     *         type="integer",
     *     ),
     *     @SWG\Parameter(
     *         description="签名",
     *         in="formData",
     *         name="session_key",
     *         required=true,
     *         type="string",
     *     )
     * )
     */
    public function login()
    {
        $post = $this->input->post();
        if (isset($post['tel']) && isset($post['code']) && isset($post['session_key'])) {
            $type = isset($post['type']) ? $post['type'] : '';
            //$res    = $this->confirm_code_gerenal($post['tel'], $post['code']);
            $result = $this->shopuser_model->login($post['tel'], $post['session_key'], $type);
            if ($result) {
                send_json(array('code' => 2000, 'data' => '', 'msg' => "验证成功"));
            } else {
                send_json(array('code' => 4002, 'data' => '', 'msg' => "验证失败"));
            }
        } else {
            send_json(array('code' => 4001, 'data' => '', 'msg' => "参数不全"));
        }
    }
    //商户退出
    /**
     * @SWG\Post(
     *     summary="商户退出",
     *     path="/shopuser/logout",
     *     tags={"商户端"},
     *     operationId="logout",
     *     produces={"application/json"},
     *     @SWG\Response(
     *         response=200,
     *         description="成功",
     *     ),
     *     @SWG\Response(
     *         response="401",
     *         description="参数不全",
     *     ),
     *     @SWG\Parameter(
     *         description="签名",
     *         in="formData",
     *         name="session_key",
     *         required=true,
     *         type="string",
     *     )
     * )
     */
    public function logout()
    {
        $post                = $this->input->post();
        $post['session_key'] = isset($post['session_key']) ? trim($post['session_key']) : '';
        if ($post['session_key'] && $session_key = $post['session_key']) {
            if ($userInfo = $this->db->query("select * from app_user where session_key = '$session_key'")->row_array()) {
                $this->db->query("update app_user set tel = NULL where session_key = '$session_key'");
                send_json(array('code' => 2000, 'data' => '', 'msg' => "退出成功"));
            } else {
                send_json(array('code' => 4002, 'data' => '', 'msg' => "验签失败，请重新授权登录"));
            }
        } else {
            send_json(array('code' => 4001, 'data' => '', 'msg' => "参数错误"));
        }
    }

}
